const app = getApp();

Page({
  data: {
    phone: '',
    password: ''
  },

  onUsernameInput(e) {
    this.setData({ phone: e.detail.value });
  },

  onPasswordInput(e) {
    this.setData({ password: e.detail.value });
  },

  // 🧾 账号密码登录
  onLogin() {
    const ip = app.globalData.userIPInfo;
    const { phone, password } = this.data;

    if (!phone || !password) {
      wx.showToast({ title: '请输入用户名和密码', icon: 'none' });
      return;
    }

    wx.request({
      url: `${ip}/api/riders/login`,
      method: 'POST',
      header: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      data: {
        phone,
        password
      },
      success: (res) => {
        if (res.data.code === 200) {
          const token = res.data.data;
          this.handleTokenLogin(token);
        } else {
          wx.showToast({ title: res.data.message, icon: 'none' });
        }
      },
      fail: () => {
        wx.showToast({ title: '请求失败', icon: 'none' });
      }
    });
  },

  // 👤 微信登录
  onWeChatLogin() {
    const ip = app.globalData.userIPInfo;
    wx.login({
      success: (res) => {
        if (res.code) {
          wx.request({
            url: `${ip}/api/wechatLogin`,
            method: 'GET',
            data: { code: res.code },
            success: (res) => {
              if (res.data.code === 200) {
                const token = res.data.data; // 因为 token 在 data 字段中
                this.handleTokenLogin(token);
              } else {
                wx.showToast({ title: res.data.message || '登录失败', icon: 'none' });
              }              
            },
            fail: () => {
              wx.showToast({ title: '微信登录失败', icon: 'none' });
            }
          });
        }
      }
    });
  },

  // 🌟 登录后通用处理：拿 token，再拿 riderId
  handleTokenLogin(token) {
    const ip = app.globalData.userIPInfo;

    // 存储 token
    wx.setStorageSync('token', token);
    app.globalData.ridertoken = token;

    // 获取骑手 ID
    wx.request({
      url: `${ip}/api/riders/getriderid?token=`+token,
      method: 'GET',
      header: {
        'Authorization': 'Bearer ' + token
      },
      success: (res) => {
        if (res.data.code === 200) {
          const riderId = res.data.data;

          // 存储 riderId
          wx.setStorageSync('riderId', riderId);
          app.globalData.riderId = riderId;
          // 跳转到主页
          wx.switchTab({
            url: '/pages/home/index'
          });          
        } else {
          wx.showToast({ title: '获取骑手ID失败', icon: 'none' });
        }
      },
      fail: () => {
        wx.showToast({ title: '请求骑手ID失败', icon: 'none' });
      }
    });
  }
});
